<template>
  <div class="system-dic-container">
    <el-card shadow="hover">
      <!--   搜索部分   -->
      <div class="system-user-search mb15">
        <el-input size="small" v-model="searchName" placeholder="请输入字典名称" style="max-width: 180px"> </el-input>
        <el-button size="small" type="primary" @click="getRoleList(pageRole.current,pageRole.size,searchName)" class="ml10" icon="el-icon-search">查询</el-button>
        <el-button size="small" type="success" class="ml10" icon="el-icon-folder-add" @click="onOpenAddRole">新增角色</el-button>
      </div>

      <!--   表格数据   -->
      <el-table :data="pageRole.records" style="width: 100%">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="roleName" label="角色名称" show-overflow-tooltip></el-table-column>
        <el-table-column label="排序" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="角色状态" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status==1">启用</el-tag>
            <el-tag type="info" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="describ" label="角色描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="text" @click="onOpenEditRole(scope.row,scope.row.status)">修改</el-button>
            <el-button :disabled="scope.row.roleName === '超级管理员'" size="small" type="text" @click="onRowDel(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--   分页   -->
      <el-pagination
          @size-change="onHandleSizeChange"
          @current-change="onHandleCurrentChange"
          class="mt15"
          :page-sizes="[5, 10, 15,20,30]"
          :page-size="5"
          :current-page="pageRole.current"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageRole.total"
      >
      </el-pagination>


      <!--   新增角色对话框   -->
      <el-dialog :title="title" :visible.sync="isShowDialog" width="769px" :before-close="DialogClose">
        <el-form :model="ruleForm" size="small" label-width="90px">
          <el-row :gutter="35">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" >
              <el-form-item label="角色名称">
                <el-input v-model="ruleForm.roleName" placeholder="请输入角色名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" >
              <el-form-item label="角色状态">
                <el-switch v-model="ruleForm.status" inactive-value="0" active-value="1" inline-prompt active-text="启" inactive-text="禁"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="角色描述">
                <el-input v-model="ruleForm.describ" type="textarea" placeholder="请输入角色描述" maxlength="150"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" >
              <el-form-item label="菜单权限">
                <el-tree  ref="tree" :data="menuList" :props="menuProps" node-key="id" show-checkbox class="menu-data-tree" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="small">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="small">确 定</el-button>
				</span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>


<script>
import role from '@/api/role'
import {deleteMenu, getMenuAdmin} from '@/api/menu'
import roleMenu from "@/api/roleMenu";

export default {
  name: "systemRole",
  data(){
    return{
      title: "", // 对话框的title
      pageRole: {}, // 角色分页对象
      searchName: "", // 搜索条件
      isShowDialog: false, // 对话框的显示
      ruleForm: {}, // 表单数据
      menuList: [], // 权限菜单
      menuProps: {  //配置选项
        children: 'children',
        label: (data)=>{
          return data.meta.title
        }
      },
    }
  },
  created() {
    this.getRoleList()
    this.getMenuList()
  },
  methods: {
    // 新增角色
    onOpenAddRole(){
      this.title = "新增角色"
      this.isShowDialog = true
    },
    DialogClose(){
      this.onCancel()
    },
    // 修改角色
    onOpenEditRole(row,status){
      this.title = "修改角色"
      this.isShowDialog = true
      let stringify= JSON.stringify(row); //转成字符串
      this.ruleForm =JSON.parse(stringify);//转回去
      roleMenu.getPageRoles(this.ruleForm.id).then(resp => {
        let keys = new Array();
        for (let i = 0; i < resp.data.length; i++) {
          if (resp.data[i].menu.parentId==0 && resp.data[i].menu.name=="home"){
            keys[i] = resp.data[i].menuId
          }else if (resp.data[i].menu.parentId!=0){
            keys[i] = resp.data[i].menuId
          }
        }
        this.$refs.tree.setCheckedKeys(keys);
      })
    },
    // 删除角色信息
    onRowDel(id){
      this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        role.deleteRoleById(id).then(resp => {
          this.$message({message: resp.message,type: 'success'});
          this.getRoleList()
          this.ruleForm = {}
        })
      }).catch( () => {
        this.$message({type: 'info',message: '已取消删除'})
      })
    },
    // 取消角色新增或修改
    onCancel(){
      this.isShowDialog = false
      this.ruleForm = {}
      this.$refs.tree.setCheckedKeys([]);
    },
    // 提交表单数据
    onSubmit(){
      let menuArray1 = this.$refs.tree.getCheckedKeys();
      let menuArray2 = [];
      for (let i=0;i<this.$refs.tree.getCheckedNodes().length;i++){
        menuArray2[i] = this.$refs.tree.getCheckedNodes()[i].parentId
      }
      let menuIds = new Set([...menuArray1,...menuArray2])
      menuIds = [...menuIds]
      menuIds.splice(menuIds.findIndex(item => item == 0),1)
      if (this.title == "新增角色"){
        role.addRole(this.ruleForm,menuIds).then(resp => {
          this.$message({message: resp.message ,type: 'success'});
        })
      }else{
        role.updateRole(this.ruleForm,menuIds).then(resp => {
          this.$message({message: resp.message ,type: 'success'});
        })
      }
      this.ruleForm = {}
      this.getRoleList()
      this.isShowDialog = false

    },
    // 获取所有角色带分页带条件
    getRoleList(currentPage=1,limit=5,name=""){
      role.getPageRoles(currentPage,limit,name).then(resp => {
        this.pageRole = resp.data
      })
    },
    // 页大小改变触发
    onHandleSizeChange(val){
      this.getRoleList(this.pageRole.current,val,name)
    },
    // 当前页改变触发
    onHandleCurrentChange(val){
      this.getRoleList(val,this.pageRole.size,name)
    },
    // 获取所有菜单项
    getMenuList() {
      getMenuAdmin().then(resp => {
        this.menuList = resp.data
      })
    }
  },
}


</script>


<style>


</style>